package com.ruoyi.tb.lmt.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;
import java.util.Map;

import com.ruoyi.common.excel.ExcelResult;
import com.ruoyi.tb.lmt.domain.vo.TbWorktemplateVo;
import lombok.RequiredArgsConstructor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.tb.lmt.domain.vo.TbMaterialVo;
import com.ruoyi.tb.lmt.domain.bo.TbMaterialBo;
import com.ruoyi.tb.lmt.service.ITbMaterialService;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 物资基础资料
 *
 * @author ruoyi
 * @date 2023-11-30
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/xha-lmt/material")
public class TbMaterialController extends BaseController {

    private final ITbMaterialService iTbMaterialService;

    /**
     * 查询物资基础资料列表
     */
    //@SaCheckPermission("xha-lmt:material:list")
    @GetMapping("/list")
    public TableDataInfo<TbMaterialVo> list(TbMaterialBo bo, PageQuery pageQuery) {
        return iTbMaterialService.queryPageList(bo, pageQuery);
    }

    /**
     * 导出物资基础资料列表
     */
    @SaCheckPermission("xha-lmt:material:export")
    @Log(title = "物资基础资料", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(TbMaterialBo bo, HttpServletResponse response) {
        List<TbMaterialVo> list = iTbMaterialService.queryList(bo);
        ExcelUtil.exportExcel(list, "物资基础资料", TbMaterialVo.class, response);
    }

    /**
     * 获取物资基础资料详细信息
     *
     * @param ID 主键
     */
    //@SaCheckPermission("xha-lmt:material:query")
    @GetMapping("/{ID}")
    public R<TbMaterialVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable Long ID) {
        return R.ok(iTbMaterialService.queryById(ID));
    }

    /**
     * 新增物资基础资料
     */
    @SaCheckPermission("xha-lmt:material:add")
    @Log(title = "物资基础资料", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody TbMaterialBo bo) {
        return toAjax(iTbMaterialService.insertByBo(bo));
    }

    /**
     * 修改物资基础资料
     */
    @SaCheckPermission("xha-lmt:material:edit")
    @Log(title = "物资基础资料", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody TbMaterialBo bo) {
        return toAjax(iTbMaterialService.updateByBo(bo));
    }

    /**
     * 删除物资基础资料
     *
     * @param IDs 主键串
     */
    @SaCheckPermission("xha-lmt:material:remove")
    @Log(title = "物资基础资料", businessType = BusinessType.DELETE)
    @DeleteMapping("/{IDs}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] IDs) {
        return toAjax(iTbMaterialService.deleteWithValidByIds(Arrays.asList(IDs), true));
    }

    //导入模板
    @SaCheckPermission("xha-lmt:material:excelExport")
    @RequestMapping(value = "/excel/export")
    public void export(HttpServletRequest request, HttpServletResponse response){
        iTbMaterialService.export(request,response);
    }

    //批量导入
//    @SaCheckPermission("xha-lmt:material:excelUpdate")
//    @PostMapping(value = "/excel/update")
//    public R<Map> updateExcel(@RequestPart("file") MultipartFile file) throws Exception{
//        return R.ok(iTbMaterialService.updateExcel(file));
//    }

    /**
     * 查询规格型号
     */
    //@SaCheckPermission("xha-lmt:material:selectBySpecs")
    @GetMapping("/list/selectBySpecs")
    public  List<TbMaterialVo> selectBySpecs(String specs) {
        return iTbMaterialService.selectBySpecs(specs);
    }


    //导入物资基础资料
    @SaCheckPermission("xha-lmt:material:excelUpdate")
    @PostMapping(value = "/excel/update", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public R<List<TbMaterialVo>> updateExcel(@RequestPart("file") MultipartFile file) throws Exception {
        // 处理解析结果
        ExcelResult<TbMaterialVo> excelResult = ExcelUtil.importExcel(file.getInputStream(), TbMaterialVo.class,true);
        // 获取从 excelResult.getList() 中获取的 TbMaterialVo 列表
        List<TbMaterialVo> voList = excelResult.getList();
        // 创建更新和新增的列表
        List<TbMaterialBo> updateList = new ArrayList<>();
        List<TbMaterialBo> addList = new ArrayList<>();

        // 遍历 TbMaterialVo 列表，根据 productCode 判断是执行更新还是新增
        for (TbMaterialVo vo : voList) {
            TbMaterialBo bo = new TbMaterialBo();
            bo.setProductcode(vo.getProductcode());
            bo.setProductname(vo.getProductname());
            bo.setSpecs(vo.getSpecs());
            bo.setMaterialQuality(vo.getMaterialQuality());
            bo.setUnits(vo.getUnits());
            bo.setUnitprice(vo.getUnitprice());
            bo.setMaterialFigureNumber(vo.getMaterialFigureNumber());
            bo.setMaterialSingleWeight(vo.getMaterialSingleWeight());
            bo.setAuthority(vo.getAuthority());
            bo.setLmtType(vo.getLmtType());
            bo.setExecutionStandardNumber(vo.getExecutionStandardNumber());
            bo.setExecutionStandardName(vo.getExecutionStandardName());
            bo.setMaterialCode(vo.getMaterialCode());
            bo.setHeadquartersStatus(vo.getHeadquartersStatus());
            bo.setBureauStatus(vo.getBureauStatus());
            bo.setSynchronizationDate(vo.getSynchronizationDate());
            bo.setRemark(vo.getRemark());
            // 根据 productCode 查询 tb_material 表中是否存在数据
            TbMaterialBo existingMaterial = iTbMaterialService.getByProductCode(bo.getProductcode());
            if (existingMaterial != null) {
                // 存在则执行更新操作
                bo.setID(existingMaterial.getID());
                updateList.add(bo);
            } else {
                // 不存在则执行新增操作
                addList.add(bo);
            }
        }

        // 执行更新操作
        if (!updateList.isEmpty()) {
            for (TbMaterialBo bo : updateList){
            iTbMaterialService.updateByBo(bo);
            }
        }

        // 执行新增操作
        if (!addList.isEmpty()) {
            for (TbMaterialBo bo : addList) {
                iTbMaterialService.insertByBo(bo);
            }
        }
        return R.ok();
    }
}
